<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="领料单位名称" prop="lldwName">
        <el-input
          v-model="queryParams.lldwName"
          placeholder="请输入领料单位名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="领用时间" prop="lyTime">
        <el-date-picker clearable
                        v-model="queryParams.lyTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择领用时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="课题名称" prop="ktName">
        <el-input
          v-model="queryParams.ktName"
          placeholder="请输入课题名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课题负责人" prop="ktFzr">
        <el-input
          v-model="queryParams.ktFzr"
          placeholder="请输入课题负责人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物资主管" prop="wzzg">
        <el-input
          v-model="queryParams.wzzg"
          placeholder="请输入物资主管"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发料人" prop="flr">
        <el-input
          v-model="queryParams.flr"
          placeholder="请输入发料人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="领料人" prop="llr">
        <el-input
          v-model="queryParams.llr"
          placeholder="请输入领料人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['yffy:lld:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['yffy:lld:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['yffy:lld:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['yffy:lld:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['yffy:lld:import']"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleExports"
        >导出docx</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table @row-click="clickRow" ref="table"
              highlight-current-row
              border :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
              v-loading="loading" :data="lldList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" type="index" :index="indexMethod"/>
      <el-table-column label="领料单位名称" align="center" prop="lldwName"/>
      <el-table-column label="领用时间" align="center" prop="lyTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lyTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="课题名称" align="center" prop="ktName"/>
      <el-table-column label="课题负责人" align="center" prop="ktFzr"/>
      <el-table-column label="物资主管" align="center" prop="wzzg"/>
      <el-table-column label="发料人" align="center" prop="flr"/>
      <el-table-column label="领料人" align="center" prop="llr"/>
      <!--      <el-table-column label="备注" align="center" prop="remark" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['yffy:lld:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['yffy:lld:remove']"
          >删除
          </el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleExports(scope.row)"-->
<!--            v-hasPermi="['occupation:basics:exportWord']"-->
<!--          >导出docx</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改领料单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-form ref="formDialog" :model="form" :rules="rules" label-width="110px">
        <div style="height: 65vh; overflow-y: auto;">
        <el-card class="box-card">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="领料单位名称:" prop="lldwName">
                <el-input v-model="form.lldwName" placeholder="请输入领料单位名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="领用时间:" prop="lyTime">
                <el-date-picker clearable
                                v-model="form.lyTime"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择领用时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="课题名称:" prop="ktName">
                <el-input v-model="form.ktName" placeholder="请输入课题名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="课题负责人:" prop="ktFzr">
                <el-input v-model="form.ktFzr" placeholder="请输入课题负责人"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddLldMx">添加物货明细</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteLldMx">删除</el-button>
            </el-col>
          </el-row>
          <div style="height: 25vh; overflow-y: auto;">
            <el-table border :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
                      :data="lldMxList" :row-class-name="rowLldMxIndex"
                      @selection-change="handleLldMxSelectionChange" ref="lldMx"

            >
              <el-table-column type="selection" width="50" align="center"/>
              <el-table-column label="序号" align="center" prop="index" width="50"/>
              <el-table-column label="物货名称" prop="whName">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.whName" placeholder="请输入物货名称"/>
                </template>
              </el-table-column>
              <el-table-column label="用途" prop="yt">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.yt" placeholder="请输入用途"/>
                </template>
              </el-table-column>
              <el-table-column label="规格型号" prop="ggxh">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.ggxh" placeholder="请输入规格型号"/>
                </template>
              </el-table-column>
              <el-table-column label="单位" prop="dw">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.dw" placeholder="请输入单位"/>
                </template>
              </el-table-column>
              <el-table-column label="数量" prop="sl">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.sl" placeholder="请输入数量" @input="calculateAmount(scope.row)"/>
                </template>
              </el-table-column>
              <el-table-column label="单价(元)" prop="dj">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.dj" placeholder="请输入单价(元)" @input="calculateAmount(scope.row)"/>
                </template>
              </el-table-column>
              <el-table-column label="金额(元)" prop="je">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.je" disabled placeholder="请输入金额(元)"/>
                </template>
              </el-table-column>
              <el-table-column label="备注" prop="bz">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.bz" placeholder="请输入备注"/>
                </template>
              </el-table-column>
                            <div slot="append" style="display: flex; justify-content: space-between; align-items: center; font-weight: bold;min-height: 3vh">
                              <div style="flex-basis: 80%; text-align: center;">
                                <div style=" align-items: center;">
                                  {{ '合计' }}
                                </div>
                              </div>
                              <div style="flex-basis: 20%;">
                                {{ calculateTotalAmount() + '元' }}
                              </div>
                            </div>
            </el-table>
          </div>

          <el-form-item label="有关事项说明:" prop="ygsxSm">
            <el-input :rows="1" v-model="form.ygsxSm" type="textarea" placeholder="请输入内容"/>
          </el-form-item>

          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="物资主管:" prop="wzzg">
                <el-input v-model="form.wzzg" placeholder="请输入物资主管"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发料人:" prop="flr">
                <el-input v-model="form.flr" placeholder="请输入发料人"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="领料人:" prop="llr">
                <el-input v-model="form.llr" placeholder="请输入领料人"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        </div>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改领料单对话框 -->
    <el-dialog title="修改领料单" :visible.sync="openModify" width="70%" append-to-body :fullscreen="dialogFull">
      <el-form ref="formDialog" :model="form" :rules="rules" label-width="110px">
        <div style="height: 66vh; overflow-y: auto;">
        <el-tabs type="border-card">
          <el-tab-pane label="基本信息">
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item  label="领料单位名称:" prop="lldwName">
                  <el-input v-model="form.lldwName" placeholder="请输入领料单位名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="领用时间:" prop="lyTime">
                  <el-date-picker clearable
                                  v-model="form.lyTime"
                                  type="date"
                                  value-format="yyyy-MM-dd"
                                  placeholder="请选择领用时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="课题名称:" prop="ktName">
                  <el-input v-model="form.ktName" placeholder="请输入课题名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="课题负责人:" prop="ktFzr">
                  <el-input v-model="form.ktFzr" placeholder="请输入课题负责人"/>
                </el-form-item>
              </el-col>
            </el-row>


            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddLldMx">添加</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteLldMx">删除</el-button>
              </el-col>
            </el-row>
            <div style="height: 25vh; overflow-y: auto;">
              <el-table border :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
                        :data="lldMxList" :row-class-name="rowLldMxIndex"
                        @selection-change="handleLldMxSelectionChange" ref="lldMx"

              >
                <el-table-column type="selection" width="50" align="center"/>
                <el-table-column label="序号" align="center" prop="index" width="50"/>
                <el-table-column label="物货名称" prop="whName">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.whName" placeholder="请输入物货名称"/>
                  </template>
                </el-table-column>
                <el-table-column label="用途" prop="yt">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.yt" placeholder="请输入用途"/>
                  </template>
                </el-table-column>
                <el-table-column label="规格型号" prop="ggxh">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.ggxh" placeholder="请输入规格型号"/>
                  </template>
                </el-table-column>
                <el-table-column label="单位" prop="dw">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.dw" placeholder="请输入单位"/>
                  </template>
                </el-table-column>
                <el-table-column label="数量" sortable prop="sl">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.sl" placeholder="请输入数量" @input="calculateAmount(scope.row)"/>
                  </template>
                </el-table-column>
                <el-table-column label="单价(元)" sortable prop="dj">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.dj" placeholder="请输入单价(元)" @input="calculateAmount(scope.row)"/>
                  </template>
                </el-table-column>
                <el-table-column label="金额(元)" sortable prop="je">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.je" disabled placeholder="请输入金额(元)"/>
                  </template>
                </el-table-column>
                <el-table-column label="备注" prop="bz">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.bz" placeholder="请输入备注"/>
                  </template>
                </el-table-column>

                              <div slot="append" style="display: flex; justify-content: space-between; align-items: center; font-weight: bold;min-height: 3vh;background-color: #D0CECE">
                                <div style="flex-basis: 80%; text-align: center;">
                                  <div style=" align-items: center;">
                                    {{ '合计' }}
                                  </div>
                                </div>
                                <div style="flex-basis: 20%;">
                                  {{ calculateTotalAmount() + '元' }}
                                </div>
                              </div>

              </el-table>
            </div>

            <el-form-item label="有关事项说明:" prop="ygsxSm">
              <el-input :rows="1" v-model="form.ygsxSm" type="textarea" placeholder="请输入内容"/>
            </el-form-item>

            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="物资主管:" prop="wzzg">
                  <el-input v-model="form.wzzg" placeholder="请输入物资主管"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="发料人:" prop="flr">
                  <el-input v-model="form.flr" placeholder="请输入发料人"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="领料人:" prop="llr">
                  <el-input v-model="form.llr" placeholder="请输入领料人"/>
                </el-form-item>
              </el-col>
            </el-row>

          </el-tab-pane>

          <el-tab-pane label="领料单附件">
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <!-- 上传按钮 -->
                <el-button size="mini" icon="el-icon-upload" type="primary" @click="lldFjShangChuan">上传</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteLldFj">删除</el-button>
              </el-col>
            </el-row>
            <el-table border :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
                      :data="lldFjList" :row-class-name="rowLldFjIndex" @selection-change="handleLldFjSelectionChange"
                      ref="lldFj">
              <el-table-column type="selection" width="50" align="center"/>
              <el-table-column label="序号" align="center" prop="index" width="50"/>
              <el-table-column label="文件名称" prop="fileName" align="center" :formatter="getFileNames"/>
              <el-table-column label="文件大小" prop="fileSize" align="center" width="120"/>
              <el-table-column label="操作" align="center" width="120">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleDownload(scope.row)"
                  >下载
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
        </div>
      </el-form>
      <template slot="title">
        <div class="avue-crud__dialog__header">
            <span class="el-dialog__title">
              修改领料单
            </span>
          <div class="avue-crud__dialog__menu" @click="dialogFull? dialogFull=false: dialogFull=true">
            <i class="el-icon-full-screen"></i>
          </div>
        </div>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 附件上传弹窗 -->
    <el-dialog title="附件上传" :visible.sync="fjShangChuan" width="25%" append-to-body center>
      <div class="upload-container">
        <el-upload
          multiple
          :action="uploadFileUrl"
          :before-upload="handleBeforeUpload"
          :file-list="fileList"
          :limit="20"
          :on-error="handleUploadError"
          :on-exceed="handleExceed"
          :on-success="handleUploadSuccess"
          :show-file-list="false"
          :headers="headers"
          class="upload-file-uploader"
          ref="fileUpload"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">
            请上传
            <template> 大小不超过 <b style="color: #f56c6c">{{ 50 }}MB</b></template>
            <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
            的文件
          </div>
        </el-upload>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  addLld,
  delLld, exportWord,
  getLld,
  insertLldFjBylldId,
  listLld,
  selectLldFjList,
  selectLldMxByLldId,
  selectMAXId,
  updateLld
} from "@/api/yffy/lld";
import {getToken} from "@/utils/auth";

export default {
  name: "Lld",
  data() {
    return {
      dialogFull:false, //用来控制弹窗
      selectedRow: null, //保存当前选中的行
      openModify: false, //修改弹窗
      fjShangChuan: false, //附件上传弹窗
      //要修改的 项目id
      lldIdEdit: "",
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
      fileList: [],
      headers: {Authorization: "Bearer " + getToken()},
      number: 0,
      uploadList: [],
      fileType: ["doc", "xls", "ppt", "txt", "pdf", "docx", "zip"],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedLldMx: [],
      // 子表选中数据
      checkedLldFj: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 领料单表格数据
      lldList: [],
      // 领料单附件表格数据
      lldFjList: [],
      // 领料明细表格数据
      lldMxList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        lldwName: null,
        lyTime: null,
        ktName: null,
        ktFzr: null,
        wzzg: null,
        flr: null,
        llr: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        lldwName: [
          {required: true, message: "领料单位名称不能为空", trigger: "blur"}
        ],
        lyTime: [
          {required: true, message: "领用时间不能为空", trigger: "blur"}
        ],
        ktName: [
          {required: true, message: "课题名称不能为空", trigger: "blur"}
        ],
        ktFzr: [
          {required: true, message: "课题负责人不能为空", trigger: "blur"}
        ],
        wzzg: [
          {required: true, message: "物资主管不能为空", trigger: "blur"}
        ],
        flr: [
          {required: true, message: "发料人不能为空", trigger: "blur"}
        ],
        llr: [
          {required: true, message: "领料人不能为空", trigger: "blur"}
        ],
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/yffy/lld/importData"
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //控制选中的行
    clickRow(row) {
      this.selectedRow = row; // 更新选中的行
      const table = this.$refs.table;
      const selectedRows = table.selection;

      // 如果点击的行已经被选中，则取消选中
      // if (selectedRows.includes(row)) {
      //   table.toggleRowSelection(row);
      // } else {
        // 否则取消之前选中的行，并选中当前点击的行
        selectedRows.forEach(selectedRow => {
          table.toggleRowSelection(selectedRow);
        });
        table.toggleRowSelection(row);
      // }
    },
    //导出word按钮操作
    handleExports() {
      const row = this.selectedRow; // 获取当前选中的行
      const queryParams = this.queryParams;
      const lldId = row.lldId || this.lldId; // Assuming lldId is defined somewhere in your component
      this.$confirm('是否确认导出word文档?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.loading = true
        return exportWord(queryParams, lldId); // Passing lldId to the exportWord function
      }).then(response => {
        this.$download.resource('/profile/upload/' + response.msg);
        this.loading = false
      }).catch(() => {});
    },
    objectSpanMethod() {
      this.$nextTick(x => {
        if (this.$refs.lldMx.$el) {
          var current = this.$refs.table.$el
            .querySelector(".el-table__footer-wrapper")
            .querySelector(".el-table__footer");

          var cell = current.rows[0].cells;
          cell[0].style.display = "none";
          cell[1].style.display = "none";
          cell[2].style.display = "none";
          cell[3].style.display = "none";
          cell[4].style.display = "none";
          cell[5].style.display = "none";
          cell[6].style.display = "none";
          cell[7].classList.remove('is-left')
          cell[7].colSpan = "8";
        }
      })
    },
    getNodeSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      let arr = ['je']
      columns.forEach((column, index) => {
        if (index === 4) {
          sums[index] = "合计";
          return;
        }
        if (arr.some(x => column.property === x)) {
          sums[index] = 0;
          data.map((item) => {
            let num = item[column.property];
            sums[index] = this.accAdd(sums[index], num);
          });
          sums[index] = sums[index] + "元";
        } else if (index === 9) {
          //备注信息 可以在这
          sums[index] = "";
        } else {
          sums[index] = "";
        }
      })
      return sums;
    },
    accAdd(arg1, arg2) {
      let r1, r2, m;
      try {
        r1 = arg1.toString().split(".")[1].length;
      } catch (e) {
        r1 = 0;
      }
      try {
        r2 = arg2.toString().split(".")[1].length;
      } catch (e) {
        r2 = 0;
      }
      m = Math.pow(10, Math.max(r1, r2));
      return ((arg1 * m + arg2 * m) / m).toFixed(2);  //四舍五入后小数点后2位
    },
    calculateTotalAmount() {
      return this.lldMxList.reduce((total, item) => total + Number(item.je), 0);
    },
    calculateAmount(row) {
      row.je = row.sl * row.dj; // 计算金额
    },
    // 文件下载处理
    handleDownload(row) {
      const resource = row.fileName;
      // 默认方法
      this.$download.resource(resource);
    },
    // 自定义编号
    indexMethod(index) {
      let pageNum = this.queryParams.pageNum - 1;
      if ((pageNum !== -1 && pageNum !== 0)) {
        return (index + 1) + (pageNum * this.queryParams.pageSize);
      } else {
        return (index + 1)
      }
    },
    // 获取文件原名
    getFileNames(row) {
      // 从路径中提取文件名
      return row.fileName.split('/').pop(); // 返回文件名部分
    },
    //上传文件之前的钩子
    handleBeforeUpload(file) {
      let that = this;
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name.split('.');
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
        // 校检文件大小
        if (this.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.fileSize;
          if (!isLt) {
            this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
            return false;
          }
        }
        this.$modal.loading("正在上传文件，请稍候...");
        this.number++;
        return true;
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs !== '' ? strs.substr(0, strs.length - 1) : '';
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading();
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传成功
    handleUploadSuccess(res, file) {
      let that = this;
      if (res.code === 200) {
        this.uploadList.push({name: res.fileName, url: res.fileName, size: that.formatFileSize(file.size)});
        let itemFile = {
          "lldId": that.lldIdEdit,
          "fileName": res.fileName,
          "fileSize": that.formatFileSize(file.size)
        };
        // 添加数据
        insertLldFjBylldId(itemFile).then(resFil => {
          that.getLldFjList();
        })
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.fileUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
      this.fjShangChuan = false
    },
    // 查询附件列表
    getLldFjList() {
      let that = this;
      selectLldFjList(that.lldIdEdit).then(resFileList => {
        that.lldFjList = resFileList.data;
      })
    },
    // 显示文件大小为KB, MB, GB, TB
    formatFileSize(size) {
      if (size === 0) return '0 Bytes';
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
      const i = Math.floor(Math.log(size) / Math.log(k));
      return parseFloat((size / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    // 获取文件名称
    getFileName(name) {
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));
        this.$modal.closeLoading();
      }
    },

    lldFjShangChuan() {
      this.fjShangChuan = true;
    },
    // 查询领料单列表
    getList() {
      this.loading = true;
      listLld(this.queryParams).then(response => {
        this.lldList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openModify = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        lldId: null,
        lldwName: null,
        lyTime: null,
        ktName: null,
        ktFzr: null,
        ygsxSm: null,
        wzzg: null,
        flr: null,
        llr: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.lldFjList = [];
      this.lldMxList = [];
      this.resetForm("formDialog");
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置按钮操作
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.lldId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 新增按钮操作
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加领料单";
    },
    // 修改按钮操作
    handleUpdate(row) {
      this.reset();
      const lldId = row.lldId || this.ids
      this.lldIdEdit = row.lldId
      getLld(lldId).then(response => {
        this.form = response.data;
        this.lldFjList = response.data.lldFjList;
      });
      selectLldMxByLldId(lldId).then(res => {
        this.lldMxList = res.data.lldMxList;
      })
      this.openModify = true;
      this.title = "修改领料单";
    },
    // 提交按钮
    submitForm() {
      this.$refs["formDialog"].validate(valid => {
        if (valid) {
          this.form.lldFjList = this.lldFjList;
          this.form.lldMxList = this.lldMxList;
          if (this.form.lldId != null) {
            updateLld(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.openModify = false;
            });
            this.getList();
          } else {
            addLld(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              selectMAXId().then(res => {
                this.lldIdEdit = res.data;
                this.openModify = true;
                this.lldFjList = [];
                getLld(this.lldIdEdit).then(response => {
                  this.form = response.data;
                })
              })
              // selectMAXId().then(res => {
              //   console.log(res.data())
              //   // this.lldIdEdit = res.data;
              //   // this.openModify = true;
              //   // getLld(this.lldIdEdit).then(response => {
              //   //   this.form = response.data;
              //   // })
              // })
            });
          }
        }
      });
    },
    // 删除按钮操作
    handleDelete(row) {
      const lldIds = row.lldId || this.ids;
      this.$modal.confirm('是否确认删除领料单编号为"' + lldIds + '"的数据项？').then(function () {
        return delLld(lldIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    // 领料明细序号
    rowLldMxIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    // 领料明细添加按钮操作
    handleAddLldMx() {
      let obj = {};
      obj.whName = "";
      obj.yt = "";
      obj.ggxh = "";
      obj.dw = "";
      obj.sl = "";
      obj.dj = "";
      obj.je = "";
      obj.bz = "";
      this.lldMxList.push(obj);
    },
    // 领料明细删除按钮操作
    handleDeleteLldMx() {
      if (this.checkedLldMx.length === 0) {
        this.$modal.msgError("请先选择要删除的领料明细数据");
      } else {
        const lldMxList = this.lldMxList;
        const checkedLldMx = this.checkedLldMx;
        this.lldMxList = lldMxList.filter(function (item) {
          return checkedLldMx.indexOf(item.index) === -1
        });
      }
    },
    // 复选框选中数据
    handleLldMxSelectionChange(selection) {
      this.checkedLldMx = selection.map(item => item.index)
    },
    // 领料单附件序号
    rowLldFjIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    // 领料单附件添加按钮操作
    handleAddLldFj() {
      let obj = {};
      obj.fileName = "";
      obj.fileSize = "";
      this.lldFjList.push(obj);
    },
    // 领料单附件删除按钮操作
    handleDeleteLldFj() {
      if (this.checkedLldFj.length === 0) {
        this.$modal.msgError("请先选择要删除的领料单附件数据");
      } else {
        const lldFjList = this.lldFjList;
        const checkedLldFj = this.checkedLldFj;
        this.lldFjList = lldFjList.filter(function (item) {
          return checkedLldFj.indexOf(item.index) === -1
        });
      }
    },
    // 复选框选中数据
    handleLldFjSelectionChange(selection) {
      this.checkedLldFj = selection.map(item => item.index)
    },
    // 导出按钮操作
    handleExport() {
      this.download('yffy/lld/export', {
        ...this.queryParams
      }, `lld_${new Date().getTime()}.xlsx`)
    },
    // 下载模板操作
    importTemplate() {
      this.download('yffy/lld/importTemplate', {}, `template_${new Date().getTime()}.xlsx`)
    },
    // 导入按钮操作
    handleImport() {
      this.upload.title = "领料单导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>

<style>
.upload-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>
